package com.kunyi.web.im.websocket;

import com.alibaba.fastjson.JSONObject;
import com.kunyi.web.im.websocket.handler.TextWebSocketFrameHandler;
import com.kunyi.web.serviceapi.im.entity.dto.MessageDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @ClassName TransportService
 * @Description 会话管理类
 * @Author zhenguo.zhuang
 * @Date 2024/03/29
 * @Version 1.0
 **/
@Slf4j
@Component
public class TransportService {
    /**
     * 保存所有连接对应的handler
     */
    public ConcurrentMap<String, TextWebSocketFrameHandler> sessions = new ConcurrentHashMap<>();



    /**
     * @author: zhenguo.zhuang
     * @Description 获得
     * @Date 16:44 2024/3/29
     * @Param uuid:
     * @return void
     **/
    public ConcurrentMap<String, TextWebSocketFrameHandler> getSession(){
       return sessions;
    }

    /**
     * @author: zhenguo.zhuang
     * @Description 移除会话
     * @Date 16:44 2024/3/29
     * @Param uuid:
     * @return void
     **/
    public void deregisterSession(String uuid){
        sessions.remove(uuid);
    }

    /**
     * @author: zhenguo.zhuang
     * @Description 保存新的会话
     * @Date 16:44 2024/3/29
     * @Param uuid:
	 * @Param handler:
     * @return void
     **/

    public void registerSessions(String uuid, TextWebSocketFrameHandler handler){
        sessions.put(uuid, handler);
    }

    /**
     * @author: zhenguo.zhuang
     * @Description 将消息发送给对应的handler
     * @Date 16:45 2024/3/29
     * @Param msg:  消息
	 * @Param topic: 需要发送的主题
     * @return void
     **/
    public void sendMsg(MessageDto dto){
        //查找出所有订阅过该主题的客户端对应的handler 将消息发送出去 实现了消息私发
        sessions.forEach((uuid, handler) -> {
            //如果为系统类消息，可以直接发送
            if(dto.getTopic().equals("/system/message")){
                handler.sendMsg(JSONObject.toJSONString(dto));
            //当前通道如果订阅了该消息，则发送
            }else if(handler.subscribeTopicList.contains(dto.getTopic())){
                handler.sendMsg(JSONObject.toJSONString(dto));
            }
        });
    }

}
